<template>
  <div class="container">
    <div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form>
            <el-form-item label="对象名称：">
              <el-input
                v-model="person.name"
                placeholder="请输入"
                style="width: 200px"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form>
            <el-form-item label="对象类型：">
              <el-select v-model="person.client" placeholder filterable>
                <el-option
                  v-for="item in person.clientList"
                  :key="item.CLIENT_NO"
                  :label="item.CLIENT_NAME"
                  :value="item.CLIENT_NO"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form style="float: left">
            <el-button size="mini" type="primary" @click="getlistdata"
              >查 询</el-button
            >
            <el-button size="mini" type="success" @click="handleAdd"
              >新 增</el-button
            >
            <!-- <el-button style="padding: 0; border: 0">
              <el-upload
                action="/上传文件的接口"
                :on-change="onChange"
                :auto-upload="false"
                :show-file-list="false"
                accept=".xls, .xlsx"
                class="upload"
              >
                <el-button size="mini" type="success">导 入</el-button>
              </el-upload>
            </el-button> -->
            <el-button size="mini" type="warning" @click="exportExcel"
              >导 出</el-button
            >
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      highlight-current-row
      border
    >
<!-- ID，ITEMID项目ID，ITEMNAME项目名称，OBJECTTYPEID对象类型ID，OBJECTTYPE对象类型名称，
OBJECTID对象ID，NAME对象名称，INTIME加入时间，INMARK加入原因，INUSER加入人，， -->

      <el-table-column
        prop="NAME"
        label="对象名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="OBJECTTYPE"
        label="对象类型"
        align="center"
        width="200"
      ></el-table-column>
      <el-table-column
        prop="ITEMNAME"
        label="项目名称"
        align="center"
        width="200"
      ></el-table-column>
      
      <el-table-column prop="INTIME" label="加入时间" align="center"></el-table-column>
      <el-table-column prop="INMARK" label="加入原因" align="center"></el-table-column>
      <el-table-column prop="INUSER" label="加入人" align="center"></el-table-column>
      <el-table-column prop="OUTTIME" label="移除时间" align="center"></el-table-column>
      <el-table-column prop="OUTUSER" label="移除人" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 新增人员 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="show"
      width="800px"
      :modal="false"
    >
      <el-form
        ref="formSave"
        :model="formSave"
        label-width="110px"
        class="flex"
      >
        <!--  -->
        <el-form-item label="对象类型">
          <el-select
            v-model="formSave.OBJECTTYPEID"
            placeholder="请选择对象类型"
            @change="changeType"
          >
            <el-option
              v-for="item in objectTypeList"
              :key="item.ID"
              :label="item.OBJECTTYPE"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="对象名称">
          <el-select
            v-model="formSave.OBJECTID"
            placeholder="请选择对象"
            filterable
            clearable
          >
            <el-option
              v-for="item in objectList"
              :key="item.ID"
              :label="item.NAME"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="INUSER" label="加入人">
          <el-input
            v-model="formSave.INUSER"
            placeholder="请输入加入人姓名"
            style="width: 207px"
          ></el-input>
        </el-form-item>
        <el-form-item prop="INMARK" label="加入原因">
          <el-input
            v-model="formSave.INMARK"
            placeholder="请输入加入原因"
            style="width: 207px"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="负责项目">
          <el-select
            v-model="arrItems"
            placeholder="请选择考评小组"
            multiple
            collapse-tags
          >
            <el-option
              v-for="item in itemList"
              :key="item.ITEMNAME"
              :label="item.ITEMNAME"
              :value="item.ITEMNAME"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'
import { formatDate } from '@/common/js/date.js'
import export2Excel from '@/utils/exportExcel/index.js'
export default {
  data () {
    return {
      arrWorktime:[],
      arrTypes: [],
      arrItems: [],
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      // 人员管理
      person: {
        name: '',
        client: localStorage.getItem('CLIENT_NO'),
        clientList: []
      },
      show: false,
      // 新增人员
      formSave: {
      },
      tableData: [],
      originalData: [],
      teamList: [],
      itemList: [],
      objectTypeList: [],
      objectList: [],
      areaList: [],
      areaListByteam: [],
      objectTypeListAll: [],
      addDialogTitle: '',
      object:{
        '11':[],
        '12':[],
      }
    }
  },
  mounted () {
    this.GetObject1()
    this.GetObject2()
    this.GetObject3()
    this.GetObject4()
    this.GetObject5()
    this.GetObject6()
    this.GetObject7()
    this.GetObject8()
    this.GetObject9()
    this.GetObject10()
    
    this.GetItemAssess()
    this.getObjectTypeList();
    this.getlistdata()
    this.GetTeamAssess()
  },
  methods: {
    async GetTeamAssess () {
      const { data } = await this.$Http.get('Assess/GetTeam_Assess?CLIENT_NO=' + localStorage.getItem('CLIENT_NO') + '&TYPE=2')
      this.person.clientList = data;
      this.person.clientList.unshift({ "CLIENT_NO": localStorage.getItem('CLIENT_NO'), "CLIENT_NAME": "全部" })
    },
    changeType (id) {
      this.objectList = this.object[id]
      console.log(this.objectList)
    },
    async getObjectTypeList () {
      var url = 'Assess/GetObjectType_Assess?ITEMID=0&OBJECTTYPE='
      let { data } = await this.$Http.get(url)
      this.objectTypeList = data
      // this.objectTypeList = Object.assign({}, data);
      // this.objectTypeListAll = data
      // this.objectTypeListAll.unshift({ ID: "0", OBJECTTYPE: "全部", ITEMNAME: "全部" })
    },
    async GetObject1 () {
      // 机扫 道路
      const { data } = await this.$Http.get('Vehicle/GetRoadInfoPB?ClientNO=' + localStorage.getItem('CLIENT_NO'))
      data.forEach(element => {
        element.NAME = element.RNAME
      });
      this.object['1'] = data
    },
    async GetObject2 () {
      // 机扫 车辆
      const { data } = await this.$Http.get('Vehicle/GetVehicleInfoPB?ClientNo=' + localStorage.getItem('CLIENT_NO'))
      data.forEach(element => {
        element.ID = element.VID
        element.NAME = element.LICENSE_PLATE
      });
      this.object['2'] = data
    },
    async GetObject3 () {
      // 人工 道路
      const { data } = await this.$Http.get('Worker/GetRoadInfoPBNew?ClientNo=' + localStorage.getItem('CLIENT_NO'))
      data.forEach(element => {
        element.NAME = element.ROADNAME
      });
      this.object['3'] = data
    },
    async GetObject4 () {
      // 人工 人员
      const { data } = await this.$Http.get('DataListCompany/GetWorkerListApi?ClientNo=' + localStorage.getItem('CLIENT_NO'))
      data.forEach(element => {
        element.ID = element.VID
      });
      this.object['4'] = data
    },
    async GetObject5 () {
      // 公厕
      const { data } = await this.$Http.get('CarService/getPlaceToilet?CLIENT_NO=' + localStorage.getItem('CLIENT_NO'))
      this.object['5'] = data
    },
    async GetObject6 () {
      // 垃圾收运 垃圾车
      const { data } = await this.$Http.get('RubbishVehicle/GetRubbishVehicleInfo?ClientNO=' + localStorage.getItem('CLIENT_NO'))
      data.forEach(element => {
        element.ID = element.VID
        element.NAME = element.LICENSE_PLATE
      });
      this.object['6'] = data
    },
    async GetObject7 () {
      // 垃圾收运 垃圾点
      const { data } = await this.$Http.get('CarService/getPlaceGarbagePoint?CLIENT_NO=' + localStorage.getItem('CLIENT_NO'))
      data.forEach(element => {
        element.NAME = element.POINTNAME
      });
      this.object['7'] = data
    },
    async GetObject8 () {
      // 中转站
      const { data } = await this.$Http.get('CarService/getPlaceStation?CLIENT_NO=' + localStorage.getItem('CLIENT_NO'))
      this.object['8'] = data
    },
    async GetObject9 () {
      // 处理厂
      const { data } = await this.$Http.get('CarService/getPlaceFactory?CLIENT_NO=' + localStorage.getItem('CLIENT_NO'))
      this.object['9'] = data
    },
    async GetObject10 () {
      // 垃圾分类 垃圾点
      const { data } = await this.$Http.get('RubbishClassification/GetRubbishScoreRoom?ClientNo=' + localStorage.getItem('CLIENT_NO'))
      data.forEach(element => {
        element.NAME = element.垃圾点名称
      });
      this.object['10'] = data
    },
    async GetItemAssess () {
      var url = 'Assess/GetCheckItem_Assess?KEY='
      const { data } = await this.$Http.get(url)
      this.itemList = data
    },
    // async getTypeAssess () {
    //   var url = 'Assess/GetCheckType_Assess?TYPENAME='
    //   const { data } = await this.$Http.get(url)
    //   this.objectTypeList = data
    // },
    // async GetAreaAssess () {
    //   const { data } = await this.$Http.get('Assess/GetArea_Assess?CLIENT_NO=' + localStorage.getItem('CLIENT_NO') + '&AREANAME=')
    //   // var arr = []
    //   // data.forEach(element => {
    //   //   var aa = {}
    //   //   aa.options = this.teamList.filter(item => item.PARENT_NO === element.CLIENT_NO)
    //   //   aa.label = element.AREANAME
    //   //   arr.push(aa)
    //   // });
    //   this.areaList = data
    // },
    // changeTeam (str) {
    //   var arrItem = this.teamList.filter(item => item.CLIENT_NO === str)[0]
    //   this.formSave.WORKAREA = arrItem.PARENT_NO
    // },
    async getlistdata () {
      const { data } = await this.$Http.get('Assess/GetBadList_Assess?ITEMID=&OBJECTTYPE=&NAME=&CLIENT_NO=' + this.person.client)
      this.originalData = data
      this.screeningData()
    },
    // 模糊查询
    screeningData () {
      this.currentPage = 1
      this.tableData = this.originalData
      // if (this.person.client !== localStorage.getItem('CLIENT_NO')) this.tableData = this.tableData.filter(item => item.CLIENT_NO === this.person.client)
      if (this.person.name) this.tableData = this.tableData.filter(item => item.NAME.includes(this.person.name))
    },
    // 打开新增窗口
    handleAdd () {
      this.addDialogTitle = '新增黑名单信息'
      //清空编辑框
      this.formSave = {}
      // this.arrTypes = []
      // this.objectTypeList.forEach(element => {
      //   this.arrTypes.push(element.TYPENAME)
      // });
      // this.arrItems = []
      // this.itemList.forEach(element => {
      //   this.arrItems.push(element.ITEMNAME)
      // });
      // this.arrWorktime = ['08:00','17:00']
      //展示窗口
      this.show = true;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      this.formSave = Object.assign({}, row);
      // this.arrTypes = []
      // if (this.formSave.WORKTYPE === '全部') {
      //   this.objectTypeList.forEach(element => {
      //     this.arrTypes.push(element.TYPENAME)
      //   });
      // } else {
      //   this.arrTypes = this.formSave.WORKTYPE.split(',')
      // }
      // this.arrItems = []
      // if (this.formSave.WORKITEM === '全部') {
      //   this.itemList.forEach(element => {
      //     this.arrItems.push(element.ITEMNAME)
      //   });
      // } else {
      //   this.arrItems = this.formSave.WORKITEM.split(',')
      // }
      // this.arrWorktime = this.formSave.WORKTIME.split('-')
      this.addDialogTitle = '编辑黑名单信息'
      this.show = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.addDialogTitle == '新增黑名单信息') {
        this.formSave.ID = '0'
        this.formSave.title = '新增'
      } else {
        this.formSave.title = '编辑'
      }
      // console.log(this.objectTypeList)
      // var itemStr = ''
      // this.objectTypeList.forEach(element => {
      //   if (element.ID === this.formSave.OBJECTTYPEID) {
      //     itemStr = element.ITEMNAME
      //   }
      // });
      var itemType = this.objectTypeList.filter(item => item.ID === this.formSave.OBJECTTYPEID)[0]
      var itemItem = this.itemList.filter(item => item.ITEMNAME === itemType.ITEMNAME)[0]
      this.formSave.ITEMID = itemItem.ID
      // if (this.arrTypes.length === this.objectTypeList.length) {
      //   this.formSave.WORKTYPE = ''
      // } else {
      //   this.formSave.WORKTYPE = this.arrTypes.join(',')
      // }
      // if (this.arrItems.length === this.itemList.length) {
      //   this.formSave.WORKITEM = ''
      // } else {
      //   this.formSave.WORKITEM = this.arrItems.join(',')
      // }
      // this.formSave.WORKTIME = this.arrWorktime.join('-')
      this.addPerson()
    },
    async addPerson () {
      console.log(this.formSave)
      this.$axios({
        url: 'Assess/SaveBad_Assess',
        method: 'post',
        data: this.formSave
      }).then(res => {
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('黑名单'+this.formSave.title+'成功')
          this.getlistdata();
          this.show = false
        } else {
          this.$message.error('黑名单'+this.formSave.title+'失败' + '，' + res.data.Message);
        }
      })
    },
    // 删除
    async handleDelete (index, row) {
      this.formSave = Object.assign({}, row);
      this.formSave.ID = -this.formSave.ID
      this.formSave.title = '删除'
      this.addPerson()
    },
    // 导入Excel
    onChange (file, fileList) {
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"// 以字符编码的方式解析
          });

          if (workbook.SheetNames.length >= 1) {
            //  this.$message({
            //    message: "导入数据表格成功",
            //    showClose: true,
            //    type: "success"
            //  });

            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            console.log(ws)
            this.inputExcelDataLength = ws.length
            this.fullscreenLoading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            for (let i = 0, len = ws.length; i < len; i++) {
              var item = ws[i]
              //   var sheetData = {
              //     VID: item['居民电话'],
              //     RUBBISH_NAME: item["垃圾品名"],
              //     WEIGHT: item["垃圾称重"],
              //     photo: '',
              //     LONGITUDE: 0,
              //     LATITUDE: 0
              //   }
              //   let exceldata =  []
              //   exceldata.push(sheetData)
              this.addWeight(item)
            }
          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },
    async addWeight (item) {
      this.$axios({
        url: 'DataListCompany/AddWorkerApi',
        method: 'post',
        data: {
          VID: item['人员ID'],
          Name: item['姓名'],
          SimCardNo: item['通讯卡号'],
          ClientNo: item['班组编号'],
          Sex: item['性别'],
          Phone: item['电话'],
          WorkType: item['工种'],
          BirhDay: item['出生日期'],
          workdate: item['入职时间'],
        }
      }).then(res => {
        console.log(res)
        this.inputExcelDataIndex++

        if (res.data.IsSucess) {
          this.fullscreenLoading.close()
          this.$message.success('表格文件导入成功')
          this.getlistdata()
        } else {
          this.fullscreenLoading.close()
          this.$message.error('表格文件导入失败' + '，' + res.data.Message);

        }
        if (this.inputExcelDataIndex == this.inputExcelDataLength) {
          this.fullscreenLoading.close()
          if (this.strError.length == 0) {
            this.$message.success('表格文件导入成功')
            this.getlistdata()
          } else {
            // this.$message.error('表格文件导入结束<br/>' + this.strError);
            this.$message({
              message: '表格文件导入结束，' + this.strError,
              type: 'error',
              duration: 5000
            })
          }
          this.getlistdata()
        }
      })
      //   })
    },
    // 导出Excel
    exportExcel () {
      let excelName = '黑名单管理'
      const tHeader = [/*'人员ID', */'姓名', '性别', '年龄', '电话', '人员类型', '小组名称', '机构名称', '负责区域', '负责类型', '负责项目', '作业时间']
      const filterVal = [/*'ID', */'NAME', 'SEX', 'AGE', 'PHONE', 'WORKERTYPE', 'GROUP_NAME', 'CLIENT_NAME', 'WORKAREA', 'WORKTYPE', 'WORKITEM', 'WORKTIME']
      export2Excel(tHeader, filterVal, this.tableData, excelName)
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getData();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    }
  }
}
</script>
<style scoped lang='less'>
.content {
  overflow-y: scroll;
}
</style>